package com.file.parser;

import com.file.bo.Chsixj;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 学籍查询解析
 * @author anyspa
 */

@Slf4j
public class ChsixjHtmlParser {

    public ResponseData<String> parseChsixjToJson(String daId, String filePath) {
        log.info("parseChsixjToJson started, daId:{}", daId);
        String json = null;

        try {
            File input = new File(filePath);
            Document doc = Jsoup.parse(input, "UTF-8");
            boolean isNewVersion = isNewVersion(doc);
            log.info("parseChsixjToJson, daId:{}, isNewVersion:{}", daId, isNewVersion);
            Chsixj chsixj = isNewVersion ? parseChsixj_NewVersion(doc) : parseChsixj(doc);
            json = JsonUtils.convertObjectToJson(chsixj);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseChsixjToJson failed", e);
            return new ResponseData<String>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseChsixjToJson completed, daId:{}, json:{}", daId, json);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private boolean isNewVersion(Document doc) {
        boolean isNewVersion = true;
        Element rowElement = doc.select(".rowcard > .row").first();
        if (rowElement == null) {
            isNewVersion = false;
        }
        return isNewVersion;
    }

    private Chsixj parseChsixj(Document doc) {
        Chsixj chsixj = new Chsixj();

        chsixj.setName(doc.select(".img-right > h6").textNodes().get(0).text());
        chsixj.setSex(doc.select(".img-right > h6 > span").text());

        Elements pElements = doc.select(".img-right > p");

        String idNoStr = pElements.get(0).text();
        // 中文分号
        if (idNoStr.contains("：")) {
            chsixj.setIdNo(idNoStr.split("：")[1].trim());
        }
        // 英文分号
        if (idNoStr.contains(":")) {
            chsixj.setIdNo(idNoStr.split(":")[1].trim());
        }


        String nationAndBirthDate = pElements.get(1).text();

        // 汉族　1992年04月20日
        Pattern pattern = Pattern.compile("\\d{4}年\\d{2}月\\d{2}日");
        Matcher matcher = pattern.matcher(nationAndBirthDate);
        if (matcher.find()) {
            chsixj.setNationality(nationAndBirthDate.substring(0, matcher.start()).trim().replace("　", StringUtils.EMPTY));//NOSONAR
            chsixj.setDateOfBirth(matcher.group());
        }

        Elements rowCollectionItems = doc.select(".collection.card > .row.collection-item");
        for (Element collectionItem : rowCollectionItems) {
            String itemKey = collectionItem.select(".col.s4").text();
            String itemValue = collectionItem.select(".col.s8").text();

            switch (itemKey) {//NOSONAR
                case "院校":
                    chsixj.setSchoolName(itemValue);
                    break;
                case "层次":
                    chsixj.setDegree(itemValue);
                    break;
                case "院系":
                    chsixj.setSchoolDepartment(itemValue);
                    break;
                case "班级":
                    chsixj.setClassName(itemValue);
                    break;
                case "专业":
                    chsixj.setMajor(itemValue);
                    break;
                case "学号":
                    chsixj.setStudentId(itemValue);
                    break;
                case "形式":
                    chsixj.setLearningStyle(itemValue);
                    break;
                case "入学时间":
                    chsixj.setDateOfEnrollment(itemValue);
                    break;
                case "学制":
                    chsixj.setSchoolSystem(itemValue);
                    break;
                case "类型":
                    chsixj.setDiplomaClassification(itemValue);
                    break;
                case "学籍状态":
                    chsixj.setGraduation(itemValue);
                    break;
                case "在线验证码":
                    chsixj.setOnlineVerificationCode(itemValue);
                    break;
                case "更新日期":
                    chsixj.setUpdateDate(itemValue);
                    break;
            }
        }

        log.info(chsixj.toString());
        return chsixj;

    }

    private Chsixj parseChsixj_NewVersion(Document doc) {
        Chsixj chsixj = new Chsixj();
        Elements elements = doc.select(".rowcard > .row");
        if (elements.size() == 0) {
            throw new RuntimeException("parseChsixjToJson failed, html format changed.");
        }

        elements.forEach(element -> {
            switch (element.child(0).text()) {//NOSONAR
                case "姓名":
                    String name = element.child(1).text();
                    chsixj.setName(name);
                    break;
                case "性别":
                    String sex = element.child(1).text();
                    chsixj.setSex(sex);
                    break;
                case "出生日期":
                    String dateOfBirth = element.child(1).text();
                    chsixj.setDateOfBirth(dateOfBirth);
                    break;
                case "民族":
                    String nationality = element.child(1).text();
                    chsixj.setNationality(nationality);
                    break;
                case "证件号码":
                    String idNo = element.child(1).text();
                    chsixj.setIdNo(idNo);
                    break;
                case "院校":
                    String schoolName = element.child(1).text();
                    chsixj.setSchoolName(schoolName);
                    break;
                case "层次":
                    String degree = element.child(1).text();
                    chsixj.setDegree(degree);
                    break;
                case "院系":
                    String schoolDepartment = element.child(1).text();
                    chsixj.setSchoolDepartment(schoolDepartment);
                    break;
                case "班级":
                    String className = element.child(1).text();
                    chsixj.setClassName(className);
                    break;
                case "专业":
                    String major = element.child(1).text();
                    chsixj.setMajor(major);
                    break;
                case "学号":
                    String studentId = element.child(1).text();
                    chsixj.setStudentId(studentId);
                    break;
                case "学制":
                    String schoolSystem = element.child(1).text();
                    chsixj.setSchoolSystem(schoolSystem);
                    break;
                case "类型":
                    String diplomaClassification = element.child(1).text();
                    chsixj.setDiplomaClassification(diplomaClassification);
                    break;
                case "形式":
                    String learningStyle = element.child(1).text();
                    chsixj.setLearningStyle(learningStyle);
                    break;
                case "入学日期":
                    String dateOfEnrollment = element.child(1).text();
                    chsixj.setDateOfEnrollment(dateOfEnrollment);
                    break;
                case "学籍状态":
                    String graduation = element.child(1).text();
                    chsixj.setGraduation(graduation);
                    break;
                case "在线验证码":
                    String onlineVerificationCode = element.child(1).text();
                    chsixj.setOnlineVerificationCode(onlineVerificationCode);
                    break;
                case "更新日期":
                    String updateDate = element.child(1).text();
                    chsixj.setUpdateDate(updateDate);
                    break;
            }
        });
        return chsixj;
    }


    public static void main(String[] args) {
//		String filePath = "E:\\data\\file\\chsixj\\教育部学籍在线验证报告.html";
//        String filePath = "D:\\data\\file\\chsixj\\chsi_xjzm.html";
        String filePath = "D:\\data\\file\\chsixj\\chsi_xjzm.html";

        ChsixjHtmlParser chsixjParser = new ChsixjHtmlParser();
        String json = chsixjParser.parseChsixjToJson("", filePath).getData();
        System.out.println(json);
    }

}
